import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Tree,
  Divider,
  Checkbox,
  Dropdown,
  Icon,
} from 'antd';
import TableList from '@/components/TableList';
import { nameMaxLength, remarkMaxLength } from '@/utils/rule';
import BindPerson from './DefineBindUser';
import styles from '../search.less';

const { TextArea } = Input;
const { TreeNode } = Tree;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const DirectoryTree = Tree.DirectoryTree;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text, serverList } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text && text.id) {
        updateFn(fieldsValue, text);
      } else {
        addDataFn(fieldsValue);
      }
    });
  };

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑管控策略' : '新增管控策略'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="策略名称">
        {form.getFieldDecorator('name', {
          rules: [
            { required: true, message: '策略名称不能为空' },
            { max: nameMaxLength()[0], message: nameMaxLength()[1] },
          ],
          initialValue: (text && text.name) || '',
        })(<Input placeholder="请输入" />)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="业务处理">
        {form.getFieldDecorator('businessIds', {
          rules: [{ required: true, message: '请选择业务处理' }],
          initialValue: (text && text.businessIds && text.businessIds.split(',')) || [],
        })(
          <CheckboxGroup>
            {serverList && serverList.length
              ? serverList.map(v => {
                return (
                  <Checkbox key={v.id} value={v.dataDictValue}>
                    {v.dataDictName}
                  </Checkbox>
                );
              })
              : null}
          </CheckboxGroup>
        )}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="备注">
        {form.getFieldDecorator('note', {
          rules: [{ max: remarkMaxLength()[0], message: remarkMaxLength()[1] }],
          initialValue: (text && text.remark) || '',
        })(<TextArea style={{ minHeight: 32 }} placeholder="请输入" rows={2} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ define, loading }) => ({
  define,
  loading: loading.models.define,
}))
@Form.create()
class define extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    selectedPersonRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    bindUserVisible: false, //绑定用户
    treeDataList: [], //组织树
    orgDataList: [], //用户
    userInfo: {},
    serverList: [], //业务处理
    boundVisible: false,
  };

  columns = [
    {
      title: '策略名称',
      dataIndex: 'name',
    },
    /* {
      title: '风险等级',
      dataIndex: 'sensitiveLevel',

    },*/
    {
      title: '业务处理',
      render: (text, record) => {
        const ids = record.businessIds && record.businessIds.split(',');
        const serverList = this.state.serverList;
        let result = [];
        ids && ids.length
          ? ids.map(vo => {
            serverList && serverList.length
              ? serverList.map(vt => {
                if (vt.dataDictValue == vo) {
                  result.push(vt.dataDictName);
                }
              })
              : null;
          })
          : null;
        return result.join(',');
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: '30%',
      render: text => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      ),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.id)}>删除</a>
          <Divider type="vertical" />
          <a onClick={() => this.boundUserVisible(true, text)}>已绑人员</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleBindUserVisible(true, text)}>人员设置</a>
        </Fragment>
      ),
    },
  ];

  // 已绑人员
  boundUserVisible = (flag, text) => {
    this.setState({
      boundVisible: !!flag,
      text: text,
    });
  };

  //批量删除
  batchDelete = (rows = []) => {
    const ids = rows
      .map(item => {
        return item.id;
      })
      .join(',');
    this.deleteData(ids); //批量删除
  };

  deleteData = id => {
    console.info('id is:' + id);
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };
  // 删除方法
  handleDeleteData(id) {
    const { dispatch } = this.props;
    dispatch({
      type: 'define/remove',
      payload: { id },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          this.setState({ selectedRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  }



  // 分页查询列表
  pageList(dataDict, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      name: (dataDict && dataDict.name) || '',
      riskModel: 1,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'define/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.treeData(); // 组织树请求
    this.serverType();
  }

  serverType() {
    const { dispatch } = this.props;
    dispatch({
      type: 'define/serverType',
      callback: res => {
        if (res.result == 'ok') {
          this.setState({
            serverList: res.data.dataList,
          });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      });
      //点击查询
      this.pageList(fieldsValue);
    });
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
    });
  };

  // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag, userInfo) => {
    this.setState({
      bindUserVisible: !!flag,
      userInfo: userInfo,
    });
  };

  // 组织树请求
  treeData() {
    const { dispatch } = this.props;
    dispatch({
      type: 'define/getTree',
      callback: res => {
        if (res.result == 'ok') {
          this.setState({
            treeDataList: res.data,
          });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  }

  //组织人员请求
  orgList(res, pageSize = 5, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      orgId: res && res.orgId,
      strategyId: (res && res.roleId) || '',
      pageSize: pageSize,
      pageNum: pageNum,
      userName: (res && res.userName) || '',
      userCode: (res && res.userCode) || '',
    };
    dispatch({
      type: 'define/getList',
      payload: values,
      callback: res => {
        if (res.result == 'ok') {
          this.setState({
            orgDataList: res.data,
          });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  }

  //校验绑定人员接口
  bindUserRole(params) {
    const { dispatch } = this.props;
    const value = {
      strategyId: params.roleId,
      userCodeList: params.userCodeList,
    };
    dispatch({
      type: 'define/checkRule',
      payload: value,
      callback: res => {
        if (res.result == 'ok' && res.rescode == 200) {
          this.bindUserRoleFn(value);
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleBindUserVisible();
    this.setState({
      orgDataList: [], //重置
    });
  }

  //绑定人员接口
  bindUserRoleFn(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'define/bindUserRole',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    // this.handleBindUserVisible()
    // this.setState({
    //   orgDataList: [],//重置
    // })
  }

  // 更新接口
  updateFn = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      id: text.id,
      name: fields.name,
      businessIds: fields.businessIds.join(','),
      remark: fields.note,
    };
    dispatch({
      type: 'define/update',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = fields => {
    const { dispatch } = this.props;
    const params = {
      name: fields.name,
      businessIds: fields.businessIds.join(','),
      remark: fields.note,
    };
    dispatch({
      type: 'define/add',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="策略名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  render() {
    const {
      define: { data },
      loading,
      form,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      text,
      bindUserVisible,
      treeDataList,
      orgDataList,
      userInfo,
      serverList,
      boundVisible,
    } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
    };
    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible,
      orgList: this.orgList.bind(this),
      bindUserRole: this.bindUserRole.bind(this),
    };
    const boundMethods = {
      boundUserVisible: this.boundUserVisible,
    };
    return (
      <Card bordered={false}>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          text={text}
          serverList={serverList}
        />
        {bindUserVisible ? (
          <BindPerson
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            orgDataList={orgDataList}
            form={form}
            userInfo={userInfo}
          />
        ) : null}
        {boundVisible ? (
          <HasUser {...boundMethods} boundVisible={boundVisible} text={text} />
        ) : null}
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
              </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

// 已绑人员
@connect(
  state => ({
    define: state.define,
    loadingqueryDetail: state.loading.effects['define/queryDetail'],
  }),
  dispatch => ({
    queryDetail: e => dispatch({ type: 'define/queryDetail', payload: e }),
    dispatch
  })
)
class HasUser extends PureComponent {
  state = {
    selectedPersonRows: [],
  };

  handleSelectPersonRows = rows => {
    this.setState({
      selectedPersonRows: rows,
    });
  };
  columns = [
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户名',
      dataIndex: 'userCode',
      key: 'userCode'
    },
    {
      title: '操作',
      render: (text) => (
        <a onClick={() => this.cancelBind(text.userCode)}>取消绑定</a>
      ),
    },
  ];

  cancelBind = id => {
    Modal.confirm({
      title: '取消绑定',
      content: '您确定取消绑定吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleCancelBindData(id),
    });
  };

  // 取消人员绑定方法
  handleCancelBindData(userCode) {
    const { dispatch } = this.props;
    dispatch({
      type: 'define/cancelBindPerson',
      payload: { userCode },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          // this.setState({ selectedPersonRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }

      },
    });
  }
  // 分页查询列表
  pageList(text, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const { queryDetail } = this.props;
    const values = {
      id: this.props.text.id,
      pageSize,
      pageNum,
    };
    queryDetail(values);
  }

  handleStandardTableChange = pagination => {
    const { text } = this.props;
    // 分页请求
    this.pageList(text, pagination.pageSize, pagination.current - 1);
  };

  componentDidMount() {
    const { text } = this.props;
    this.pageList(text);
  }

  render() {
    const { boundVisible, boundUserVisible, loadingqueryDetail, define } = this.props;
    const { selectedPersonRows } = this.state;
    return (
      <Modal
        destroyOnClose
        width={600}
        title="已绑人员"
        visible={boundVisible}
        onCancel={() => boundUserVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => boundUserVisible()}>
            返回
          </Button>,
        ]}
      >
        <TableList
          className={styles.tdPadding}
          selectedRows={selectedPersonRows}
          loading={loadingqueryDetail}
          data={define.dataDetail}
          columns={this.columns}
          onSelectRow={this.handleSelectPersonRows}
          onChange={this.handleStandardTableChange}
          rowKey="userId"
          hideRowSelection={true}
        />
      </Modal>
    );
  }
}

export default define;
